using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using DG.Tweening;
using UnityEngine.UI;

public class UIManager : MonoBehaviour
{
    public static UIManager Instance;
    public GameObject window;
    public Text textLoading;
    private void Awake()
    {
        Instance = this;
    }

    private void Start()
    {
        ShowLoadingAction();
    }

    private void ShowLoadingAction()
    {
        textLoading.DOText("Too may clients connect.Please wait patiently.", 5).SetLoops(-1, LoopType.Yoyo);
    }

    private void KillLoadingAction()
    {
        textLoading.DOKill();
        textLoading.text = "";
    }

    private void OnDestroy()
    {
        Instance = null;
    }

    private bool _show1stUI = false;
    public void ShowUI(string uiName)
    {
        var uiGameObject = this.GetUIGameObject(uiName);
        if(uiGameObject != null)
        {
            uiGameObject.SetActive(true);
            return;
        }
        XFactory.Instance.CreateInstanceAsync(uiName, null, (vGameObject) =>
        {
            if (!_show1stUI)
            {
                _show1stUI = true;
                KillLoadingAction();
            }

            vGameObject.name = uiName;
            vGameObject.transform.SetParent(this.window.transform, false);
        });
        //Debug.LogError("can not find ui name:" + uiName);
    }

    public void CloseUI(string uiName)
    {
        var uiGameObject = this.GetUIGameObject(uiName);
        if (uiGameObject != null)
        {
            uiGameObject.SendMessage("OnHandleClose");
            uiGameObject.SetActive(false);
            return;
        }
        Debug.LogError("can not find ui name:" + uiName);
    }

    public GameObject GetUIGameObject(string uiName)
    {
        for (int i = 0; i < window.transform.childCount; i++)
        {
            var child = window.transform.GetChild(i);
            if (child.gameObject.name == uiName)
            {
                return child.gameObject;
            }
        }
        return null;
    }
}
